#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
处理剩余遗漏的中文节点
"""

import re
import shutil
from pathlib import Path

# 剩余节点映射表
REMAINING_NODE_MAPPING = {
    "号码数据预制件-原始模版": "BetData_Original_Template",
    "号码风险预制件-原始模版": "RiskData_Original_Template", 
    "C_关闭按钮": "C_Close_Button",
}

def chinese_to_unity_unicode(chinese_text):
    """将中文字符串转换为Unity格式的Unicode转义序列（大写）"""
    unicode_escaped = chinese_text.encode('unicode_escape').decode('ascii')
    # 将小写的unicode转义序列转换为大写
    return re.sub(r'\\u([0-9a-f]{4})', lambda m: f'\\u{m.group(1).upper()}', unicode_escaped)

def process_file(file_path, mappings):
    """处理单个文件"""
    if not file_path.exists():
        print(f"文件不存在: {file_path}")
        return False
    
    print(f"处理文件: {file_path}")
    
    # 创建备份
    backup_path = file_path.with_suffix('.prefab.backup3')
    shutil.copy2(file_path, backup_path)
    print(f"创建备份: {backup_path}")
    
    # 读取文件内容
    with open(file_path, 'r', encoding='utf-8') as f:
        content = f.read()
    
    original_content = content
    total_replacements = 0
    
    # 处理每个映射
    for chinese_name, english_name in mappings.items():
        unity_unicode = chinese_to_unity_unicode(chinese_name)
        pattern = rf'm_Name: "{re.escape(unity_unicode)}"'
        replacement = f'm_Name: "{english_name}"'
        
        # 计算替换次数
        matches = re.findall(pattern, content)
        if matches:
            content = re.sub(pattern, replacement, content)
            count = len(matches)
            total_replacements += count
            print(f"✓ 替换: {chinese_name} -> {english_name} ({count}次)")
        else:
            print(f"✗ 未找到: {chinese_name}")
    
    # 保存修改后的文件
    if content != original_content:
        with open(file_path, 'w', encoding='utf-8') as f:
            f.write(content)
        print(f"✓ 文件已更新，替换了 {total_replacements} 个节点名称")
        return True
    else:
        print("✗ 没有进行任何替换")
        return False

def main():
    """主函数"""
    print("=== 处理剩余遗漏的中文节点 ===\n")
    
    # 处理各个文件
    files_to_process = [
        (Path("Assets/Prefabs/C_BetData_Template.prefab"), {"号码数据预制件-原始模版": "BetData_Original_Template"}),
        (Path("Assets/Prefabs/C_RiskData_Template.prefab"), {"号码风险预制件-原始模版": "RiskData_Original_Template"}),
        (Path("Assets/Prefabs/M_Panel.prefab"), {"C_关闭按钮": "C_Close_Button"}),
    ]
    
    total_processed = 0
    for file_path, mappings in files_to_process:
        if process_file(file_path, mappings):
            total_processed += 1
        print()
    
    print(f"=== 处理完成，共处理了 {total_processed} 个文件 ===")

if __name__ == "__main__":
    main() 